package com.ruoyi.fjtseac.util.aop;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author zzl
 * @date 2022/8/3 11:46
 */
@Aspect
@Component
public class PageViewAspect {

    @Autowired
    RedisCache redisCache;

    @Pointcut("@annotation(com.ruoyi.fjtseac.util.aop.PageView)")
    public void pvPointcut() {

    }

    /**
     * 浏览量自增切面  （由于功能实现的问题，后来弃用了，改为在查询时进行数据预热）
     * @param jp
     * @return
     * @throws Throwable
     */
    @Around("pvPointcut()")
    public AjaxResult count(ProceedingJoinPoint jp) throws Throwable {
        String table = ((MethodSignature)jp.getSignature()).getMethod().getAnnotation(PageView.class).table().getTableName();
        Object[] ids = jp.getArgs();
        Integer id = (Integer) ids[0];
        String key = table + ":" + id;
        if (redisCache.getCacheObject(key) == null) {
            Integer pageView = JSON.parseObject(((AjaxResult) jp.proceed()).get("data").toString(), Integer.class);
            redisCache.setCacheObject(key, pageView);
        }else {
            redisCache.incr(key);
        }
        return AjaxResult.success((Integer) redisCache.getCacheObject(key));
    }
}
